package com.woodws.sys.service.impl;

import com.woodws.core.service.impl.BaseServiceImpl;
import com.woodws.sys.dao.SysRolePermissionDao;
import com.woodws.sys.entity.SysMenu;
import com.woodws.sys.entity.SysRolePermission;
import com.woodws.sys.service.MenuService;
import com.woodws.sys.service.RolePermissionService;
import com.woodws.sys.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by maoxiaodong on 2016/10/16.
 */
@Service
public class RolePermissionServiceImpl extends BaseServiceImpl<SysRolePermissionDao, SysRolePermission, Long>
        implements RolePermissionService {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public List<SysMenu> findUserMenus(Long userId) {
        List<Long> roleIds = userRoleService.findRoleIdByUserId(userId);
        return findUserMenus(roleIds);
    }

    @Override
    public List<SysMenu> findUserMainMenus(List<Long> roleIds) {
        List<SysMenu> menuAll = menuService.findByMain();
        filterMenu(roleIds, menuAll);
        return menuAll;
    }

    @Override
    public List<SysMenu> findUserMenus(List<Long> roleIds) {
        List<SysMenu> menuAll = menuService.findShowAll();
        filterMenu(roleIds, menuAll);
        return menuAll;
    }

    private void filterMenu(List<Long> roleIds, List<SysMenu> menuAll) {
        Set<SysRolePermission> rolePermissions = dao.findByTypeAndRoleIdIn("MENU", roleIds);
        Set<SysMenu> roleMenus = new HashSet<SysMenu>();
        for (SysRolePermission rolePermission : rolePermissions) {
            SysMenu menu = new SysMenu(rolePermission.getResourceId());
            roleMenus.add(menu);
        }
        filterMenu(menuAll, roleMenus);
    }

    private void filterMenu(List<SysMenu> menus, Set<SysMenu> roleMenus) {
        List<SysMenu> removes = new ArrayList<SysMenu>();
        for (SysMenu menu : menus) {
            if (menu.hasChildren()) {
                filterMenu(menu.getChildrenMenus(), roleMenus);
            }

            if (!roleMenus.contains(menu) && !menu.hasChildren()) {
                removes.add(menu);
            }
        }

        for (SysMenu menu : removes) {
            menus.remove(menu);
        }
    }
}
